// feedback.service.ts
import { Provide, Inject } from '@midwayjs/core';
import { InjectEntityModel } from '@midwayjs/typeorm';
import { Repository, Like, Between } from 'typeorm';
import { Feedback } from '../entity/feedBack.entity';
import { CreateFeedbackDto, UpdateFeedbackDto, FeedbackRatingDto, QueryFeedbackDto } from '../dto/feedBack.dto';

@Provide()
export class FeedbackService {
  @InjectEntityModel(Feedback)
  feedbackModel: Repository<Feedback>;

  /**
   * 创建反馈
   */
  async create(dto: CreateFeedbackDto): Promise<Feedback> {
    const feedback = this.feedbackModel.create(dto);
    return await this.feedbackModel.save(feedback);
  }

  /**
   * 更新反馈
   */
  async update(id: number, dto: UpdateFeedbackDto): Promise<Feedback> {
    const feedback = await this.feedbackModel.findOne({ where: { id } });
    if (!feedback) {
      throw new Error('反馈不存在');
    }
    
    // 如果更新状态为已处理相关状态，自动添加处理时间
    if (dto.status && ['resolved', 'closed', 'rejected'].includes(dto.status) && !feedback.handledAt) {
      dto['handledAt'] = new Date();
    }

    Object.assign(feedback, dto);
    return await this.feedbackModel.save(feedback);
  }

  /**
   * 提交评分
   */
  async submitRating(id: number, dto: FeedbackRatingDto): Promise<Feedback> {
    const feedback = await this.feedbackModel.findOne({ where: { id } });
    if (!feedback) {
      throw new Error('反馈不存在');
    }
    
    /* feedback.rating = dto.rating;
    feedback.userComment = dto.userComment; */
    
    return await this.feedbackModel.save(feedback);
  }

  /**
   * 根据ID查询反馈
   */
  async findById(id: number): Promise<Feedback> {
    const feedback = await this.feedbackModel.findOne({ where: { id } });
    if (!feedback) {
      throw new Error('反馈不存在');
    }
    return feedback;
  }

  /**
   * 查询反馈列表
   */
  async findAll(query: QueryFeedbackDto): Promise<{ list: Feedback[], total: number }> {
    const { page = 1, size = 20, keyword, createdStart, createdEnd, sortField = 'createdAt', sortOrder = 'DESC', ...where } = query;
    
    const queryBuilder = this.feedbackModel.createQueryBuilder('feedback');
    
    // 添加过滤条件
    if (where.userId) {
      queryBuilder.andWhere('feedback.userId = :userId', { userId: where.userId });
    }
    
    if (where.feedbackType) {
      queryBuilder.andWhere('feedback.feedbackType = :feedbackType', { feedbackType: where.feedbackType });
    }
    
    if (where.status) {
      queryBuilder.andWhere('feedback.status = :status', { status: where.status });
    }
    
    if (where.priority) {
      queryBuilder.andWhere('feedback.priority = :priority', { priority: where.priority });
    }
    
    if (where.isRead !== undefined) {
      queryBuilder.andWhere('feedback.isRead = :isRead', { isRead: where.isRead });
    }
    
    if (where.handlerId) {
      queryBuilder.andWhere('feedback.handlerId = :handlerId', { handlerId: where.handlerId });
    }
    
    // 关键词搜索
    if (keyword) {
      queryBuilder.andWhere('(feedback.title LIKE :keyword OR feedback.content LIKE :keyword)', 
        { keyword: `%${keyword}%` });
    }
    
    // 创建时间范围
    if (createdStart && createdEnd) {
      queryBuilder.andWhere('feedback.createdAt BETWEEN :startDate AND :endDate', {
        startDate: new Date(createdStart),
        endDate: new Date(createdEnd),
      });
    } else if (createdStart) {
      queryBuilder.andWhere('feedback.createdAt >= :startDate', { startDate: new Date(createdStart) });
    } else if (createdEnd) {
      queryBuilder.andWhere('feedback.createdAt <= :endDate', { endDate: new Date(createdEnd) });
    }
    
    // 排序
    queryBuilder.orderBy(`feedback.${sortField}`, sortOrder as 'ASC' | 'DESC');
    
    // 分页
    queryBuilder.skip((page - 1) * size).take(size);
    
    const [list, total] = await queryBuilder.getManyAndCount();
    
    return { list, total };
  }

  /**
   * 删除反馈
   */
  async remove(id: number): Promise<boolean> {
    const result = await this.feedbackModel.delete(id);
    return result.affected > 0;
  }

  /**
   * 标记已读
   */
  async markAsRead(id: number): Promise<boolean> {
    const result = await this.feedbackModel.update(id, { isRead: true });
    return result.affected > 0;
  }
}
